package leetcode.code0802;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;

//执行用时：41 ms, 在所有 Java 提交中击败了11.73%的用户
//
//内存消耗：48.3 MB, 在所有 Java 提交中击败了24.80%的用户
//
//通过测试用例：112 / 112
public class Solution extends Solution802 {

	@Override
	public List<Integer> eventualSafeNodes(int[][] graph) {
		int n = graph.length;
		int[] outs = new int[n];
		Queue<Integer> queue = new LinkedList<>();
		Set<Integer>[] hash = new HashSet[n];
		for (int i = 0; i < n; i++) {
			hash[i] = new HashSet<>();
		}
		for (int i = 0; i < n; i++) {
			int[] tos = graph[i];
			int j = graph[i].length;
			outs[i] = j;
			if (outs[i] == 0) {
				queue.add(i);
			}
			for (int k = 0; k < j; k++) {
				int to = tos[k];
				hash[to].add(i);
			}
		}
		List<Integer> ans = new ArrayList<>();
		int cur = 0;
		while (!queue.isEmpty()) {
			ans.add(cur = queue.poll());
			for (int e : hash[cur]) {
				if (--outs[e] == 0) {
					queue.add(e);
				}
			}
		}
		Collections.sort(ans);
		return ans;
	}

	public static void main(String[] args) {
		Solution so = new Solution();
//		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
	}

}
